package cn.zyjblogs.starter.oauth.resource;

import cn.zyjblogs.starter.oauth.autoconfigure.WhiteListProperties;
import cn.zyjblogs.starter.oauth.handler.ResourceAccessDeniedHandler;
import cn.zyjblogs.starter.oauth.handler.ResourceAuthenticationEntryPoint;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager;
import org.springframework.security.oauth2.provider.token.TokenStore;

import java.util.List;

/**
 * 资源服务
 *
 * @author zhuyijun
 */
@Configuration
@EnableResourceServer
@RequiredArgsConstructor
@RefreshScope
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Value("${security.oauth2.resource.id}")
    private String resourceId;
    @Value("${security.oauth2.client.scope}")
    private String scope;
    private final TokenStore tokenStore;
    private final WhiteListProperties whiteListProperties;


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                .resourceId(resourceId)
                // 验证令牌的服务
                .tokenStore(tokenStore)
                .stateless(true)
                .authenticationManager(new OAuth2AuthenticationManager())
                .accessDeniedHandler(new ResourceAccessDeniedHandler())
                .authenticationEntryPoint(new ResourceAuthenticationEntryPoint());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        List<String> allowPaths = whiteListProperties.getAllowPaths();
        String[] strings = allowPaths.toArray(new String[0]);
        String scopeRs = "#oauth2.hasAnyScope(" + '\'' + scope + '\'' + ",'all')";
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers(strings).permitAll()
                .antMatchers("/webjars/**", "/swagger-ui.html/**", "/swagger-resources/**", "/v2/api-docs/**").permitAll()
                .antMatchers("/**").access(scopeRs)
                .anyRequest()
                .authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .httpBasic();
    }

}

